package com.simblog.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.simblog.common.ClientParameter;
import com.simblog.common.SessionEntity;
import com.simblog.common.constants.Constants;
import com.simblog.common.utils.ClientParameterUtil;
import com.simblog.common.utils.MD5Util;
import com.simblog.common.utils.TokenUtil;
import com.simblog.oaknt.domain.User;
import com.simblog.oaknt.domain.UserToken;
import com.simblog.oaknt.service.IUserService;
import com.simblog.oaknt.service.IUserTokenService;

@Controller
public class UserController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(UserController.class);
	@Reference
	private IUserService userService;
	@Reference
	private IUserTokenService userTokenService;

	@ResponseBody
	@RequestMapping("p/user/login")
	public JSONObject login(String account, String password, String sign, ClientParameter clientParameter) {
		logger.info("用户登录，accout={},password={}", new Object[] { account, password });
		try {
			if (StringUtils.isBlank(account)) {
				return assemblyJson(null, Constants.PARAMETER_NULL_ERROR, "账号不能为空");
			}
			if (StringUtils.isBlank(password)) {
				return assemblyJson(null, Constants.PARAMETER_NULL_ERROR, "密码不能为空");
			}

			Map<String, Object> params = new HashMap<String, Object>();

			List<User> list = userService.check(account, MD5Util.MD5(password));

			if (list.size() == 1) {
				User user = list.get(0);
				// 保存token到mysql
				params.put("userId", user.getId());
				List<UserToken> userTokenList = userTokenService.queryList(params);

				UserToken userToken = null;
				UserToken oldUserToken = null;
				String token = TokenUtil.generateToken();

				if (CollectionUtils.isEmpty(userTokenList)) {// 插入
					userToken = new UserToken();
					userToken.setUserId(user.getId());
					userToken.setToken(token);
					userToken.setCreateTime(new Date());
					userToken.setUpdateTime(new Date());
					userToken.setExpiredTime(new Date(new Date().getTime() + 7 * 24 * 60 * 60 * 1000));
					userToken.setIsDelete("0");
					userTokenService.insert(userToken);
				} else {// 更新
					oldUserToken = userTokenList.get(0);
					userToken = userTokenList.get(0);
					userToken.setUserId(null);
					userToken.setToken(token);
					userToken.setCreateTime(null);
					userToken.setUpdateTime(new Date());
					userToken.setExpiredTime(new Date(new Date().getTime() + 7 * 24 * 60 * 60 * 1000));
					userToken.setIsDelete(null);
					userTokenService.updateByPrimaryKeySelective(userToken);
				}

				// 保存token到redis
				SessionEntity sessionEntity = new SessionEntity();
				sessionEntity.setUser(user);
				TokenUtil.setSessionEntity(token, sessionEntity);
				// 删除redis旧的数据
				if (oldUserToken != null) {
					TokenUtil.deleteSessionEntity(oldUserToken.getToken());
				}
				user.setToken(token);
				return assemblyJson(user, Constants.RESP_SUCCESS, "登录成功");
			} else {
				return assemblyJson(null, Constants.RESP_FAIL, "账号或密码错误");
			}

		} catch (Exception e) {
			logger.error("用户登录异常");
			e.printStackTrace();
			return systemException();
		}

	}

}
